package cn.com.b2office.dao.hibernate;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import cn.com.b2office.dao.SpecialItemDao;
import cn.com.b2office.domain.SpecialItem;

public class SpecialItemDaoHiberImpl extends HibernateDaoSupport implements
		SpecialItemDao {

	private static final Log logger = LogFactory
			.getLog(SpecialItemDaoHiberImpl.class);

	public int countItems(int firstResult, int size) {
		String hql = "select count(*) from SpecialItem";
		Integer count = (Integer) getHibernateTemplate().find(hql)
				.listIterator().next();
		return count.intValue();
	}

	public int countItems(int sectionId, int firstResult, int size) {
		String hql = "select count(*) from SpecialItem where sectionid=:sectionId";
		Session session = getSession();
		Integer count = (Integer) session.createQuery(hql).setInteger(
				"sectionId", sectionId).uniqueResult();
		releaseSession(session);
		return count.intValue();
	}

	@SuppressWarnings("unchecked")
	public List<SpecialItem> listItems(int firstResult, int size) {
		List<SpecialItem> list = null;
		String hql = "from SpecialItem order by sortWeight desc";
		Session session = getSession();
		try {
			Query query = session.createQuery(hql).setFirstResult(firstResult)
					.setMaxResults(size);
			// 查询缓存
			query.setCacheable(true);
			list = query.list();
		} catch (RuntimeException e) {
			logger.error("listItems error. " + e.getMessage());
			throw e;
		} finally {
			releaseSession(session);
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	public List<SpecialItem> listItems(int sectionId, int firstResult, int size) {
		List<SpecialItem> list = null;
		String hql = "from SpecialItem where sectionId=:sectionId order by sortWeight desc";
		Session session = getSession();
		try {
			Query query = session.createQuery(hql).setInteger("sectionId",
					sectionId).setFirstResult(firstResult).setMaxResults(size);
			// 查询缓存
			query.setCacheable(true);
			list = query.list();
		} catch (RuntimeException e) {
			logger.error("listItems error. " + e.getMessage());
			throw e;
		} finally {
			releaseSession(session);
		}
		return list;
	}

}
